// 全局控制
var is_debug = false; //生产模式(false)输出到output文件夹 开发模式(true)则输出到output_dev文件夹
var is_rev = false; //部署缓存解决方案  即替换静态资源名字
var is_jshinit = false;//js语法检查

//gulp plugin
var gulp = require('gulp');
var less = require('gulp-less');    //解析less
var cssnano = require("gulp-cssnano");  //压缩css
var uglify = require("gulp-uglify");    //压缩js
var htmlmin = require("gulp-htmlmin");      //压缩html
var clean = require("gulp-clean");      //清理目录
var extender = require('gulp-html-extend');     //html合并 <!-- @@include /footer.html {"foo":"bar"} -->
var autoprefixer = require('gulp-autoprefixer');     //根据设置浏览器版本自动处理浏览器前缀
var browserSync = require('browser-sync').create();     //自动刷新
var addsrc = require('gulp-add-src');   //添加额外的文件流
var sourcemaps = require('gulp-sourcemaps');    //css生成source map
var notify = require('gulp-notify'); //报错处理
var combiner2 = require('stream-combiner2');
var jshint = require('gulp-jshint'); //js语法检查
var gulpif = require('gulp-if');
var plumber = require('gulp-plumber');
var rev = require('gulp-rev');
var revCollector = require("gulp-rev-collector");
var gulpsync = require('gulp-sync')(gulp);
//var babel = require('gulp-babel');

// 自定义文件
var handleErrors = require('./gulp/util/handleErrors');
var jshintConfig = require('./gulp/util/jshintConfig');
var getConfig = require('./gulp/util/gulpConfig');

var is_reload = false; //watch任务用到

//  打包目录
var __DIST__ = 'output'; //   /usr/local/tomcat  output  C:/Users/win7/Desktop/output
var __DIST__dev = 'output_dev'; //   /usr/local/tomcat   output_dev  C:/Users/win7/Desktop/output_dev
var config;

if(true == is_debug){
    config = getConfig(__DIST__dev);
}else {
    config = getConfig(__DIST__);
}

gulp.task("clean", function () {
    return gulp.src(config.build, {read: false}).pipe(clean({force: true}));
});

gulp.task('release', function () {
    is_debug = false;
    config = getConfig(__DIST__);
    gulp.start(gulpsync.sync(['clean',['file','less','js','css','html'],'rev'],'release-task'));
});

gulp.task('release-dev', function () {
    is_debug = true;
    config = getConfig(__DIST__dev);
    gulp.start(gulpsync.sync(['clean',['file','less','js','css','html'],'rev'],'release-task'));
});


gulp.task('default',function () {
    gulp.start(gulpsync.sync(['clean',['file','less','js','css','html'],'rev','server','watch'],'default-task'));
});

gulp.task('server', function () {
    var port = 3200;
    browserSync.init({
        server: {
            baseDir: config.build
        },
        open: false,
    });
    //browserSync.init({
    //    ui: {
    //        port: port + 1,
    //        weinre: {
    //            port: port + 2
    //        }
    //    },
    //    port: port,
    //    startPath: '/',
    //    proxy: 'localhost:8080',
    //    open: false,
    //});
});

gulp.task('watch', function () {
    if(is_rev){
        gulp.watch('src/**/*.less', gulpsync.sync(['less','rev'],'watch-less'));
        gulp.watch('src/**/*.js', gulpsync.sync(['js','hint-js','rev'],'watch-js'));
        gulp.watch('src/**/*.html', gulpsync.sync(['html','rev'],'watch-html'));
        gulp.watch('src/*.html', gulpsync.sync(['html','rev'],'watch-html'));
        gulp.watch('src/**/*.css',gulpsync.sync(['css','rev'],'watch-css'));
    }else {
        is_reload = false;
        gulp.watch('src/**/*.less', ['less']);
        gulp.watch('src/**/*.js', gulpsync.sync(['js','hint-js'],'watch-js'));
        gulp.watch('src/**/*.html', ['html']);
        gulp.watch('src/*.html', ['html']);
        gulp.watch('src/**/*.css',['css']);
    }
});

gulp.task('less', function() {
    return combiner2.obj([
        gulp.src(config.less.compile),
        gulpif(is_debug,sourcemaps.init()),
        less(),
        autoprefixer(),
        gulpif(is_debug,sourcemaps.write()),
        gulpif(is_rev,rev()),
        gulp.dest(config.less.dest),
        gulpif(is_rev,rev.manifest()),
        gulpif(is_rev,gulp.dest(config.rev.less_css)),
        browserSync.reload({stream: true})
    ]).on('error', handleErrors);
});


gulp.task('js',function(){
    return gulp.src(config.js.all)
        //.pipe(babel({ presets: ['es2015']})) 
        .pipe(gulpif(!is_debug,uglify()))
        .pipe(gulpif(is_rev,rev()))  //set hash key
        .pipe(gulp.dest(config.build))
        .pipe(gulpif(is_rev,rev.manifest())) //set hash key json
        .pipe(gulpif(is_rev,gulp.dest(config.rev.js)))
        .pipe(gulpif(is_reload,browserSync.reload({stream: true})));
});

gulp.task('hint-js',function(){
    if(is_jshinit){
        return gulp.src(config.js.hint)
            .pipe(jshint(jshintConfig))
            .pipe(jshint.reporter("jshint-stylish"))
            //.pipe(customerReporter)
            ;
    }
});

gulp.task('css', function() {

    var combined = combiner2.obj([
        gulp.src(config.css.all),
        autoprefixer(),
        gulpif(!is_debug,cssnano()),
        gulpif(is_rev,rev()),
        gulp.dest(config.build),
        gulpif(is_rev,rev.manifest()),
        gulpif(is_rev,gulp.dest(config.rev.css)),
        gulpif(is_reload,browserSync.reload({stream: true}))
    ]);
    combined.on('error', handleErrors);
    return combined;
});


gulp.task('html', function() {
    return gulp.src(config.html.all)
        .pipe(extender({annotations:true,verbose:false}))
        .pipe(gulpif(!is_debug,htmlmin({collapseWhitespace: true})))
        .pipe(gulp.dest(config.build))
        .pipe(gulpif(is_reload,browserSync.reload({stream: true})));
});

gulp.task('rev', function () {
    if(is_rev){

        return gulp.src([config.rev.revJson, config.rev.buildHtml])
            .pipe( revCollector({
                replaceReved: true,
            }) )
            .pipe( gulp.dest(config.build))
            .pipe(browserSync.reload({stream: true}));
    }
});

gulp.task('file', function() {
    return gulp.src([
        'src/**/*.jpg',
        'src/**/*.png',
        'src/**/*.gif',
        'src/**/*.ico'])
        .pipe(addsrc([
            'src/**/*.otf',
            'src/**/*.eot',
            'src/**/*.svg',
            'src/**/*.swf',
            'src/**/*.ttf',
            'src/**/*.woff',
            'src/**/*.woff2',
            'src/**/*.json']))
        .pipe(gulp.dest(config.build));
});
